package com.ruoyi.project.module.ny;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.project.domain.YhTemplateField;
import com.ruoyi.project.module.ny.utils.TemplateTool;
import com.ruoyi.project.module.ny.vo.FieldVo;
import com.ruoyi.project.module.ny.vo.TableVo;
import com.ruoyi.project.module.ny.vo.ZiduanVo;
import com.ruoyi.project.service.ISysConfigService;
import com.ruoyi.project.service.IYhTemplateFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.*;

@RestController
@RequestMapping("ny/dcfield")
public class NyYhTemplateFieldController extends BaseController {

    @Autowired
    private ISysConfigService iSysConfigService;

    @Autowired
    private IYhTemplateFieldService yhTemplateFieldService;

    public NyYhTemplateFieldController() throws IOException {
    }

    /**
     * 查询模板字段列表
     */
    //@RequiresPermissions("project:dcfield:list")
    @GetMapping("/list")
    public TableDataInfo list(YhTemplateField yhTemplateField)
    {
        List<YhTemplateField> list = yhTemplateFieldService.selectYhTemplateFieldList(yhTemplateField);
//        System.out.println(list);
        return getDataTable(list);
    }

    /**
     * 导出模板字段列表
     */
    //@RequiresPermissions("project:dcfield:export")
    @Log(title = "模板字段", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YhTemplateField yhTemplateField)
    {
        List<YhTemplateField> list = yhTemplateFieldService.selectYhTemplateFieldList(yhTemplateField);
        ExcelUtil<YhTemplateField> util = new ExcelUtil<YhTemplateField>(YhTemplateField.class);
        util.exportExcel(response, list, "模板字段数据");
    }

    /**
     * 获取模板字段详细信息
     */
    //@RequiresPermissions("project:dcfield:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(yhTemplateFieldService.selectYhTemplateFieldById(id));
    }

    /**
     * 新增模板字段
     */
    //@RequiresPermissions("project:dcfield:add")
    @Log(title = "模板字段", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YhTemplateField yhTemplateField)
    {
        return toAjax(yhTemplateFieldService.insertYhTemplateField(yhTemplateField));
    }

    /**
     * 修改模板字段
     */
    //@RequiresPermissions("project:dcfield:edit")
    @Log(title = "模板字段", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YhTemplateField yhTemplateField)
    {
        return toAjax(yhTemplateFieldService.updateYhTemplateField(yhTemplateField));
    }

    /**
     * 删除模板字段
     */
    //@RequiresPermissions("project:dcfield:remove")
    @Log(title = "模板字段", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yhTemplateFieldService.deleteYhTemplateFieldByIds(ids));
    }

    /**
     * 获取数据库字段信息
     */
    //@RequiresPermissions("project:dcfield:remove")
    @Log(title = "模板字段", businessType = BusinessType.DELETE)
    @PostMapping("/getfield")
    public List getfields(@RequestBody TableVo vo) {

        //根据模板number查询对应的字段信息
        YhTemplateField field =  new YhTemplateField();
        field.setTemplateNumber(vo.getTableNumber());
        field.setFieldSwitchStatus("01");//导出01状态的信息
        field.setFieldDeriveStatus("01");//导出01状态的信息
        List<YhTemplateField> listField = yhTemplateFieldService.selectYhTemplateFieldList(field);//得到指定模板的字段信息list
        List arrList = new ArrayList();//返回字段的list集合

        if(listField.size()>0) {
            //查询数据库获得字段对应的comment，执行了数据库表查询步骤(数据库中使用的表名和字段名应为标准下划线形式)
            Map<String,String> map = getColumnComments(listField.get(0).getDatabankName());
            for (int i = 0; i < listField.size(); i++) {
//            if (map.containsKey(listField.get(i).getFieldName())) {
                ZiduanVo ziduanVo = new ZiduanVo();
                ziduanVo.setNameCn(listField.get(i).getFieldName());
                ziduanVo.setNameEn(listField.get(i).getFieldNumber());
                arrList.add(ziduanVo);
//            }
            }
        }
        return arrList;
    }
    @Log(title = "所有字段", businessType = BusinessType.OTHER)
    @GetMapping("/getAllField/{tableName}/{templateNumber}")
    public List getAllFields(@PathVariable String tableName,@PathVariable String templateNumber) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        String[] strArray = {"id","note1", "note2", "note3","note4", "note5", "note6","note7", "note8", "note9","note10", "userId","deptId"};
        //通过返回的数据库中的表名，实例化实体类，返回字段信息
        String className = TemplateTool.underscoreToCamelCase(tableName); // 要查找的 VO 类名
        String result = className.substring(0, 1).toUpperCase() + className.substring(1);
        String fullClassName = "com.ruoyi.project.domain." + result; // 假设 VO 类在 com.example.vo 包下

        Class<?> voClass = Class.forName(fullClassName);
        Constructor<?> constructor = voClass.getConstructor();
        Object voInstance = constructor.newInstance();
        Field[] fields = voClass.getDeclaredFields();
        List<FieldVo> fieldNames = new ArrayList<>();

        Map<String,String> map = getColumnComments(tableName);//驼峰式

        List<YhTemplateField> templateFields = yhTemplateFieldService.selectYhTemplateFieldByNumber(templateNumber);

        if(templateFields.size()>0){
            for(int i = 0;i<templateFields.size();i++){
                FieldVo vo = new FieldVo();
                vo.setId(templateFields.get(i).getId());
                vo.setFieldName(templateFields.get(i).getFieldName());
                vo.setFieldSeq(templateFields.get(i).getFieldSeq());
                if(templateFields.get(i).getFieldDeriveStatus()!=null&&templateFields.get(i).getFieldDeriveStatus().equals("01")){
                    vo.setFieldDeriveStatus(true);//开启
                }else{
                    vo.setFieldDeriveStatus(false);
                }
                if(templateFields.get(i).getFieldSwitchStatus()!=null&&templateFields.get(i).getFieldSwitchStatus().equals("01")){
                    vo.setFieldSwitchStatus(true);//开启
                }else{
                    vo.setFieldSwitchStatus(false);
                }
                vo.setFieldKind(templateFields.get(i).getFieldKind());
                vo.setFieldNumber(templateFields.get(i).getFieldNumber());
                fieldNames.add(vo);
            }
            return fieldNames;
        }else {
            long i = 1;
            for (Field field : fields) {
                FieldVo vo = new FieldVo();
                if (map.containsKey(field.getName())) {
                    if (!Arrays.asList(strArray).contains(field.getName())) {
                        vo.setFieldName(map.get(field.getName()));
                        vo.setFieldNumber(field.getName());
                        vo.setFieldDeriveStatus(true);//对
                        vo.setFieldSwitchStatus(true);
                        vo.setFieldSeq(i++);
                        vo.setFieldKind(field.getType().getName());
                        fieldNames.add(vo);
                    }
                }
            }
        }
        System.out.println(fieldNames);
        return fieldNames;
    }

    @Log(title = "所有字段", businessType = BusinessType.OTHER)
    @PostMapping("/updateAllField")
    public int insertAllFields(@RequestBody List<YhTemplateField> list) {

        List<YhTemplateField> templateFields = yhTemplateFieldService.selectYhTemplateFieldByNumber(list.get(0).getTemplateNumber());

        if(templateFields.size()==0){
            for (int i=0;i<list.size();i++){
                YhTemplateField tempVo = list.get(i);
                YhTemplateField  vo = new YhTemplateField();
                vo.setTemplateId(list.get(0).getTemplateId());
                vo.setTemplateNumber(list.get(0).getTemplateNumber());
                vo.setTemplateName(list.get(0).getTemplateName());
                vo.setTemplateStatus(list.get(0).getTemplateStatus());
                vo.setDatabankName(list.get(0).getDatabankName());
                vo.setDatabankNumber(list.get(0).getDatabankNumber());
                vo.setFieldNumber(tempVo.getFieldNumber());
                vo.setFieldKind(tempVo.getFieldKind());
                vo.setFieldSeq((long) tempVo.getFieldSeq());
                vo.setFieldName(tempVo.getFieldName());
                if(Boolean.parseBoolean(tempVo.getFieldDeriveStatus())){
                    vo.setFieldDeriveStatus("01");
                }else{
                    continue;
                }
                if(Boolean.parseBoolean(tempVo.getFieldSwitchStatus())){
                    vo.setFieldSwitchStatus("01");
                }else{
                    vo.setFieldSwitchStatus("00");
                }
                yhTemplateFieldService.insertYhTemplateField(vo);//添加字段数据信息
            }
            return 1;
        }else{
            for(int i = 0;i<list.size();i++){

                YhTemplateField yhTemplateField = list.get(i);
                if(Boolean.parseBoolean(yhTemplateField.getFieldDeriveStatus())){
                    yhTemplateField.setFieldDeriveStatus("01");//开启
                }else{
                    yhTemplateField.setFieldDeriveStatus("02");
                }
                if(Boolean.parseBoolean(yhTemplateField.getFieldSwitchStatus())){
                    yhTemplateField.setFieldSwitchStatus("01");//开启
                }else{
                    yhTemplateField.setFieldSwitchStatus("02");
                }
                yhTemplateFieldService.updateYhTemplateField(yhTemplateField);
            }
            return 2;
        }
    }

    public Map<String, String> getColumnComments(String tableName) {
        Map<String, String> map = new HashMap<>();

        String url = iSysConfigService.selectConfigByKey("sys.project.event.url");
        String user = iSysConfigService.selectConfigByKey("sys.project.event.user");
        String password = iSysConfigService.selectConfigByKey("sys.project.event.password");

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String sql = "SELECT column_name AS columnName, column_comment AS columnComment FROM information_schema.columns WHERE TABLE_SCHEMA = 'yh-hospitalevent' AND TABLE_NAME = 'he_report_event'";
//            System.out.println(sql);
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {
                while (rs.next()) {
                    String name = rs.getString("columnName");
                    String comment = rs.getString("columnComment");
                    map.put(TemplateTool.underscoreToCamelCase(name), comment);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map;
    }
}
